#!/usr/bin/env node

/**
 * 测试连接清理功能
 * 验证代理服务器停止时是否正确关闭所有活跃连接
 */

import { NetworkFirewallApp } from "../src/app.js";
import https from 'https';

console.log("🧪 测试连接清理功能");
console.log("==================\n");

const app = new NetworkFirewallApp();

async function makeHttpsRequest() {
  return new Promise((resolve, reject) => {
    const request = https.get('https://www.baidu.com', {
      timeout: 5000
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({ status: res.statusCode, data: data.length }));
    });

    request.on('error', reject);
    request.on('timeout', () => {
      request.destroy();
      reject(new Error('请求超时'));
    });
  });
}

async function testConnectionCleanup() {
  try {
    console.log("📋 第1步: 启动应用");
    await app.start();
    
    console.log("\n📋 第2步: 检查初始连接状态");
    let status = app.proxyServer.getStatus();
    console.log("初始连接状态:", status.activeConnections);
    
    console.log("\n📋 第3步: 发起HTTPS请求");
    try {
      const result = await makeHttpsRequest();
      console.log(`请求成功: ${result.status}, 数据长度: ${result.data}`);
    } catch (error) {
      console.log(`请求失败: ${error.message}`);
    }
    
    console.log("\n📋 第4步: 检查请求后连接状态");
    status = app.proxyServer.getStatus();
    console.log("请求后连接状态:", status.activeConnections);
    
    console.log("\n📋 第5步: 停止代理服务");
    const stopStart = Date.now();
    await app.stopProxy();
    const stopDuration = Date.now() - stopStart;
    console.log(`代理停止耗时: ${stopDuration}ms`);
    
    console.log("\n📋 第6步: 检查停止后连接状态");
    status = app.proxyServer.getStatus();
    console.log("停止后连接状态:", status.activeConnections);
    
    if (status.activeConnections.total === 0) {
      console.log("\n✅ 测试通过: 所有连接已正确关闭");
    } else {
      console.log("\n❌ 测试失败: 仍有活跃连接未关闭");
    }
    
    console.log("\n📋 第7步: 验证HTTPS访问恢复");
    // 等待一下让系统代理设置生效
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    try {
      const result = await makeHttpsRequest();
      console.log(`✅ HTTPS访问恢复正常: ${result.status}`);
    } catch (error) {
      console.log(`❌ HTTPS访问仍有问题: ${error.message}`);
    }
    
  } catch (error) {
    console.error("❌ 测试过程中发生错误:", error.message);
  } finally {
    // 确保应用完全停止
    try {
      await app.stop();
    } catch (error) {
      console.error("停止应用失败:", error.message);
    }
  }
}

async function main() {
  console.log("开始连接清理测试...\n");
  
  await testConnectionCleanup();
  
  console.log("\n测试完成！");
  process.exit(0);
}

// 添加进程退出处理
process.on("SIGINT", async () => {
  console.log("\n👋 测试被中断，正在清理...");
  try {
    await app.stop();
  } catch (error) {
    console.error("清理失败:", error.message);
  }
  process.exit(0);
});

process.on("uncaughtException", async (error) => {
  console.error("\n❌ 发生未预期的错误:", error.message);
  try {
    await app.stop();
  } catch (stopError) {
    console.error("停止应用失败:", stopError.message);
  }
  process.exit(1);
});

// 运行测试
main(); 